package a10_动态规划;

/**
 * <p>
 * a30_打家劫舍2复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/2/20
 */
public class a30_打家劫舍2复习1 {
    public static void main(String[] args) {
        a30_打家劫舍2复习1 test = new a30_打家劫舍2复习1();
        test.rob(new int[]{200,3,140,20,10});
    }
    public int rob(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        int i = rob1(splitArray(nums, 0, nums.length - 2));
        int j = rob1(splitArray(nums, 1, nums.length - 1));
        return Math.max(i,j);
    }

    private int[] splitArray(int[] nums,int leftIdx,int rightIdx){
        int[] result = new int[rightIdx-leftIdx+1];
        int currentIdx = 0;
        while (leftIdx <= rightIdx){
            result[currentIdx] = nums[leftIdx];
            currentIdx++;
            leftIdx++;
        }
        return result;
    }

    //dp[i]:包含i下标的房间，最大可以获取的金额
    //递推公式：dp[i] = Math.max(nums[i-1],nums[i] + dp[i-2])
    //偷i:nums[i] + dp[i-2]
    //不偷i:nums[i-1]
    //初始化：dp[0] = nums[0] dp[1] = Math.max(nums[0],nums[1])
    private int rob1(int[] nums){
        if(nums.length == 1){
            return nums[0];
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0],nums[1]);

        for (int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i-1],nums[i] + dp[i-2]);
        }

        return dp[dp.length-1];
    }
}
